package com.community.sqlapp.service;

import com.community.sqlapp.dpsToXmind.GetFileIdMethodClass;
import com.community.sqlapp.entity.FileInfoPo;
import com.community.sqlapp.mapper.FileInfoMapper;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 文件上传，信息入库实现类
 */
@Service
public class FileInfoService {

    @Autowired
    private FileInfoMapper fileInfoMapper;

    @Autowired
    private GetFileIdMethodClass getFileIdMethodClass;

    @Autowired
    private COSClient cosClient;

    @Value("${tencent.cos.bucketname}")
    private String bucketName;

    @Value("${tencent.cos.cosurl}")
    private String cosUrl;
    /**
     * 上传文件并保存文件信息到数据库
     * @param file
     * @return
     */
    public FileInfoPo uploadFile(MultipartFile file) throws IOException {
        // 生成唯一的文件ID
        String fileId = UUID.randomUUID().toString();

        // 获取原始文件名
        String originalFileName = file.getOriginalFilename();

        // 创建文件信息对象
        FileInfoPo fileInfo = new FileInfoPo();
        try {
            // 创建临时文件
            File tempFile = File.createTempFile("upload_", "_" + originalFileName);
            // 将MultipartFile转换为临时文件
            file.transferTo(tempFile);
            // 使用GetFileIdMethodClass获取千问文件服务器返回的文件信息，传递临时文件的完整绝对路径
            String apiFileInfo = getFileIdMethodClass.getFileId(tempFile.getAbsolutePath());
            if (apiFileInfo != null && !apiFileInfo.trim().isEmpty()) {
                // 解析JSON字符串，提取id字段
                try {
                    JSONObject jsonObject = JSON.parseObject(apiFileInfo);
                    String extractedFileId = jsonObject.getString("id");
                    if (extractedFileId != null && !extractedFileId.trim().isEmpty()) {
                        //从千问文件服务器返回的文件信息中提取fileid
                        fileId = extractedFileId;
                    }
                } catch (Exception e) {
                    System.out.println("JSON解析失败: " + e.getMessage());
                }

                fileInfo.setFileIdInfo(apiFileInfo);
                fileInfo.setFileId(fileId);
            }
            // 删除临时文件
            tempFile.delete();
        } catch (Exception e) {
            // 如果GetFileIdMethodClass失败，继续使用UUID
            System.out.println("API调用失败，使用UUID作为文件ID: " + e.getMessage());
        }
        fileInfo.setFileName(originalFileName);
        // 保存到数据库
        fileInfoMapper.insertFileInfo(fileInfo);
        return fileInfo;
    }

    /**
     * 根据文件名查询文件信息
     * @param fileName
     * @return
     */
    public FileInfoPo getFileInfoByFileName(String fileName) {
        return fileInfoMapper.getFileInfoByFileName(fileName);
    }

    /**
     * 图片上传到腾讯COS，获取公网访问域名
     * @param file
     * @return
     * @throws IOException
     */
    public String uploadCOSFile(MultipartFile file) throws IOException {
        // 生成唯一文件名
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String key = "/images/" + UUID.randomUUID() + suffix;

        // 元数据
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.getSize());
        metadata.setContentType(file.getContentType());

        try (InputStream inputStream = file.getInputStream()) {
            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(bucketName, key, inputStream, metadata);
            PutObjectResult result = cosClient.putObject(putObjectRequest);
            System.out.println(result.getRequestId());
            //cosClient.shutdown();
            // 返回可访问地址
            return  cosUrl + key;
        }
    }
}
